import { Problem } from "./problem.js";
import { Game } from "./game.js";
import { copyText } from "./utils.js";

const form = layui.form;

let i_am_new_bee = false;
let current_problem_id = window.localStorage.getItem( 'problem_id' );
if ( current_problem_id == null ) {
    i_am_new_bee = true;
    current_problem_id = '1';
}

let auto_next = true;
let auto_next_str = window.localStorage.getItem( 'auto_next' );
if ( auto_next_str == null ) {
    auto_next = true;   // auto next on default.
} else {
    auto_next = auto_next_str === "true";
}

form.val('auto_next_switch_form', { 'auto_next_switch' : auto_next });


let username = window.localStorage.getItem( 'username' );

let problem = new Problem( current_problem_id );
let game = new Game( problem, switchToNextProblem, onWin, auto_next );

problem.GetProblem();
problem.GetRankList();
game.Launch();

if ( i_am_new_bee ) {
    askTheNewBee();
}

$( '#button_reset' ).on( "click", function () {
    game.ResetGame();
} )

$( '#button_next' ).on( "click", function () {
    game.moveNext();
} )

$( '#button_prev' ).on( "click", function () {
    game.movePrev();
} )

$( '#button_next_p' ).on( "click", function () {
    switchProblem( Number( current_problem_id ) + 1 );
} )

$( '#button_prev_p' ).on( "click", function () {
    switchProblem( Number( current_problem_id ) - 1 );
} )


$ ( '#head_title_edit' ).on( 'keydown', function (e) {
    const ENTER_KEY = 13;
    if (e.which != ENTER_KEY) {
        return;
    }

    e.currentTarget.blur();
} )


$ ( '#head_title_edit' ).on( 'blur', function (e) {
    let next_problem_id = e.currentTarget.innerText;
    if (isNaN(next_problem_id)) {
        alert(next_problem_id + "不是一个数字！");
        return;
    }

    switchProblem(next_problem_id);
} )


function switchToNextProblem() {
    let next_problem_id = String( Number( current_problem_id ) + 1 );
    let next_problem = new Problem( next_problem_id );

    next_problem.GetProblem();
    next_problem.GetRankList();
    if ( !next_problem.IsGotSuccess() ) {
        layer.msg( "没有更多关卡了" );
        return;
    }
    current_problem_id = next_problem_id;
    window.localStorage.setItem( 'problem_id', current_problem_id );
    game.SetProblem( next_problem );
    game.Launch();
}

function switchProblem( num ) {
    let next_problem_id = Number( num );
    let next_problem = new Problem( next_problem_id );

    next_problem.GetProblem();
    if (!next_problem.IsGotSuccess()) {
        alert("获取不到该问题， 问题 id = " + next_problem_id);
        return;
    }
    next_problem.GetRankList();
    current_problem_id = next_problem_id;
    window.localStorage.setItem( 'problem_id', current_problem_id );
    game.SetProblem( next_problem );
    game.Launch();
}


function uploadMoves( move_list, username ) {
    let ret = '';

    $.ajax( {
        async: false,
        type: "POST",
        url: "/data/upload_moves",
        data: JSON.stringify( {
            "problem_id": Number( current_problem_id ),
            "username": username,
            "move_list": move_list
        } ),
        contentType: "application/json; charset=utf-8",
        success: ( resp, status, xhr ) => {
            ret = resp;
        },
        error: function ( xhr, status, error ) {
            ret = xhr.responseText;
        }
    } );

    return ret;
}


function handleUploadMoveList( move_list ) {
    let upload_ret = '';
    let username_upload_using = username;

    console.log( move_list );
    do {
        upload_ret = uploadMoves( move_list, username_upload_using );
        console.log( upload_ret );
        if ( upload_ret === 'Accepted.') {
            // confirm( '上榜成功' );
            game.RefreshRankList();
            break;
        } else if ( upload_ret === 'Moves not accepted.' ) {
            alert( '你的步骤都不能解题!' );
            break;
        } else if ( upload_ret === 'Username already ranked.' ) {
            do {
                username_upload_using = prompt( "该名字已被使用，请输入你的另一个大名" );
            } while ( username_upload_using == null );
        } else {
            alert( '上榜失败 ' + 'Reason: ' + upload_ret );
        }
    } while ( upload_ret === 'Username already ranked.' );
}


function onWin( move_list ) {
    console.log( move_list );
    while ( username == null ) {
        username = prompt( "请输入你的大名" );
    }

    window.localStorage.setItem( 'username', username );
    handleUploadMoveList( move_list );
}


form.on( 'checkbox(auto_next_switch)', function( data ) {
    let checked = data.elem.checked;

    localStorage.setItem( 'auto_next' , String( checked ) );
    game.SetAutoNext( checked );
});


function requestRecordSynchronization( user_id ) {
    let ret = null;

    $.ajax( {
        async: false,
        type: "POST",
        url: "/data/sync?user_id=" + user_id,
        success: ( resp, status, xhr ) => {
            ret = {username : resp, status_code : status};
        },
        error: function ( xhr, status, error ) {
            ret = {msg : xhr.responseText, status_code : status};
        }
    } );

    return ret;
}


function getUserId() {
    let ret = '';

    $.ajax( {
        async: false,
        type: "GET",
        url: "/data/user_id",
        success: ( resp, status, xhr ) => {
            ret = resp;
        },
        error: function ( xhr, status, error ) {
            ret = xhr.responseText;
        }
    } );

    return ret;
}


$( '#btn_whoAmI' ).on( "click", function () {
    let user_id = getUserId();

    let username_prompt = '';
    if ( username == null ) {
        username_prompt = '不知道 （快去过一关，然后告诉我你是谁吧）';
    } else {
        username_prompt = '"' + username + '"';
    }

    if ( confirm( "你是: " + username_prompt +  "\n你的 UserID: " + user_id + "\n是否复制 UserID 到剪贴板？" ) ) {
        copyText( user_id );
    }
} )


function handleRequestSynchronization() {
    let user_id = null, resp = null;

    do {
        user_id = prompt( "请输入要同步的 UserID（或前缀）" );
        if ( user_id == null ) {
            return;
        }

        resp = requestRecordSynchronization( user_id );
        console.log(resp);
        if ( resp.msg === 'No such user.' ) {
            alert( '没有 UserID 为 ' + user_id + ' 的记录！\n请检查 UserID 是否正确' );
        } else if ( resp.msg === 'Not specific enough.' ) {
            alert( '前缀 ' + user_id + ' 匹配到多个玩家！\n请输入更长的前缀' );
        } else if ( resp.msg === 'Already be that man.' ) {
            alert( '你本来就是 "' + username + '" 啦！');
            return;
        }
    } while ( resp.status_code != 'success' );

    username = resp.username;
    window.localStorage.setItem( 'username', username );
    game.RefreshRankList();
    confirm( '同步完成，你现在就是 "' + username + '"了！' );
}


$( '#btn_reqSync' ).on( "click", function () {
    handleRequestSynchronization();
} )


function askTheNewBee() {
    if ( confirm( "欢迎来玩汽车华容道\n已有旧号？点击确定同步旧号的记录" ) ) {
        handleRequestSynchronization();
    }
}